<?php

class DibiPoSqlReflector extends DibiObject implements IDibiReflector {
    /**
     * @var IDibiDriver
     */
    private $driver;
    
    public function __construct(IDibiDriver $driver) {
        $this->driver = $driver;
    }
    
    public function getTables() {
        $result = $this->driver->query("DESCRIBE");
        $tables = array();
        while ($row = $result->fetch(false)) {
            $tables[] = array(
                'name' => $row[0],
                'view' => false
            );
        }
        return $tables;
    }
    
    public function getColumns($table) {
        $result = $this->driver->query("DESCRIBE $table");
        $columns = array();
        while ($row = $result->fetch(TRUE)) {
            $type = explode('(', $row['type']);
            $columns[] = array(
                'name'          => $row['name'],
                'table'         => $table,
                'nativetype'    => strtoupper($type[0]),
                'size'          => isset($type[1]) ? (int) $type[1] : NULL,
                'unsigned'      => false,
                'nullable'      => true,
                'default'       => $row['default'],
                'autoincrement' => $row['extra'] === 'auto_increment' ||
                        $row['extra'] === 'alias for rowid',
                'vendor'        => $row
            );
        }
        return $columns;
    }
    
    public function getIndexes($table) {
        $indexes = array();
        foreach ($this->getColumns($table) as $column) {
            if ($column['autoincrement']) {
                $indexes[$column['name']] = array(
                    'name'    => $column['name'],
                    'unique'  => true,
                    'primary' => true,
                    'columns' => array($column['name'])
                );
            }
        }
        return $indexes;
    }
    
    public function getForeignKeys($table) {
        return array(); // PoSql does not support foreign keys
    }
}
